<template>
  <div class="factor-page home-page no-scroll">

    <!-- 顶部搜索表单区 -->
    <el-card class="top-search-card" shadow="hover">
      <el-form
        ref="topFormRef"
        :model="topForm"
        label-width="100px"
        inline
        class="top-search-form">
        <el-form-item label="基金代码">
          <el-input v-model="topForm.fundCode" placeholder="请输入基金代码" />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="topForm.startDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择开始日期"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="topForm.endDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="calculateFactors" :loading="loading" plain>
            <el-icon><EditPen /></el-icon>
            实时计算</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success"  plain @click="showFundDetails">
            <el-icon><Document /></el-icon>基金信息</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="main-card module-card factor-main-card" shadow="hover">
      <!-- 因子类型Tab -->
      <el-tabs v-model="factorTab" @tab-click="handleTabChange" class="factor-type-tabs">
        <el-tab-pane label="基本因子" name="base" />
        <el-tab-pane label="衍生因子" name="derived" />
        <el-tab-pane label="风格因子" name="style" />
      </el-tabs>
      <!-- 标题与操作按钮 -->
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <div style="display: flex; align-items: center;">
              <h3 style="margin: 0; margin-right: 8px;">
                <el-icon><DataAnalysis /></el-icon>
                因子管理
              </h3>
              <el-tag type="info" size="small">
                共 {{ pagination.total }} 个因子
              </el-tag>
            </div>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="openAddFactorDialog">
              <el-icon><Plus /></el-icon>
              添加基本因子数据</el-button>
            <el-button type="warning" @click="exportFactors" icon="Download">导出数据</el-button>
          </div>
        </div>
      </template>
      <!-- 搜索区 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="因子名称"><el-input v-model="searchForm.factorName" clearable :prefix-icon="Search" placeholder="请输入因子名称" /></el-form-item>
          <el-form-item label="因子代码"><el-input v-model="searchForm.factorCode" clearable :prefix-icon="Search" placeholder="请输入因子代码" /></el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.enabled" clearable placeholder="请选择状态">
              <el-option label="启用" :value="true" />
              <el-option label="禁用" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchFactors" >
              <el-icon><Search /></el-icon>
              搜索</el-button>
            <el-button @click="resetSearch" icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 因子列表 -->
      <div class="factor-table-wrapper">
        <el-table :data="factors" :height="tableHeight" stripe border highlight-current-row v-loading="loading" style="width:100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="factorName" label="因子名称" min-width="150">
            <template #default="{ row }">
              <div class="factor-name"><el-icon class="factor-icon"><DataAnalysis /></el-icon><span>{{ row.factorName }}</span></div>
            </template>
          </el-table-column>
          <el-table-column prop="factorCode" label="因子代码" width="120" />
          <el-table-column prop="factorType" label="因子类型" width="120" align="center">
            <template #default="{ row }"><el-tag :type="getFactorTypeColor(row.factorType)">{{ getFactorTypeLabel(row.factorType) }}</el-tag></template>
          </el-table-column>
          <el-table-column prop="frequency" label="更新频率" width="100" align="center">
            <template #default="{ row }"><el-tag type="info">{{ getFrequencyLabel(row.frequency) }}</el-tag></template>
          </el-table-column>
          <el-table-column prop="updateTime" label="最后更新时间" width="180" align="center">
            <template #default="{ row }"><div class="update-time"><el-icon><Clock /></el-icon><span>{{ formatDateTime(row.updateTime) }}</span></div></template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right" align="center">
            <template #default="{ row }">
              <el-button-group>
                <el-button size="small" type="danger" @click="deleteFactor(row.id)" icon="Delete">删除</el-button>
              </el-button-group>
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty-placeholder"><el-empty description="暂无数据"><el-button type="primary" @click="resetSearch">重置过滤</el-button></el-empty></div>
          </template>
        </el-table>
      </div>
      <div class="card-pagination-fixed">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="factorDialogVisible" title="新增基本因子数据" width="600px">
      <el-form :model="factorForm" :rules="factorRules" ref="factorFormRef" label-width="100px">
        <el-form-item label="因子代码" prop="factorCode" required>
          <el-input v-model="factorForm.factorCode" placeholder="请输入因子代码" />
        </el-form-item>
        <el-form-item label="因子名称" prop="factorName" required>
          <el-input v-model="factorForm.factorName" placeholder="请输入因子名称" />
        </el-form-item>
        <el-form-item label="因子类型" prop="factorType" required>
          <el-select v-model="factorForm.factorType" placeholder="请选择因子类型">
            <el-option label="简单收益率因子" value="简单收益率因子" />
            <el-option label="年化收益率因子" value="年化收益率因子" />
            <el-option label="对数收益率因子" value="对数收益率因子" />
            <el-option label="波动率因子" value="波动率因子" />
            <el-option label="夏普比率因子" value="夏普比率因子" />
            <el-option label="最大回撤因子" value="最大回撤因子" />
            <el-option label="下行风险因子" value="下行风险因子" />
            <el-option label="相对强弱指数因子" value="相对强弱指数因子" />
            <el-option label="移动平均值因子" value="移动平均值因子" />
            <el-option label="申购开放频率因子" value="申购开放频率因子" />
            <el-option label="赎回开放频率因子" value="赎回开放频率因子" />

          </el-select>
        </el-form-item>
        <el-form-item label="基金代码" prop="fundCode" required>
          <el-input v-model="factorForm.fundCode" placeholder="请输入基金代码" />
        </el-form-item>
        <el-form-item label="因子值" prop="value" required>
          <el-input v-model.number="factorForm.value" placeholder="请输入因子值" type="number" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="factorForm.description" type="textarea" :rows="2" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="factorForm.enabled" />
        </el-form-item>
        <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="factorForm.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="更新人" prop="updatedBy">
          <el-input v-model="factorForm.updatedBy" placeholder="请输入更新人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="factorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFactorForm">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="fundInfoDialogVisible" title="基金净值明细">
      <el-table :data="navDataList">
        <el-table-column prop="date" label="日期" />
        <el-table-column prop="nav" label="净值" />
        <el-table-column prop="unitNav" label="单位净值" />
        <el-table-column prop="accumulatedNav" label="累计净值" />
        <!-- 可根据NavData结构补充更多字段 -->
      </el-table>
    </el-dialog>
    <el-dialog v-model="factorsDialogVisible" title="因子计算结果" width="600px">
      <el-table :data="factorCalcResult" border style="width: 100%">
        <el-table-column prop="name" label="因子名称" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="value" label="值" />
      </el-table>
      <template #footer>
        <el-button @click="factorsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Refresh, Edit, View, Delete,
  DataAnalysis, Check, Warning, TrendCharts, Clock,
  DataLine, Upload, Download, EditPen, Document
} from '@element-plus/icons-vue'
import axios from "axios";

const tableHeight = ref(0)
const updateTableHeight = () => { tableHeight.value = window.innerHeight - 260 }
window.addEventListener('resize', updateTableHeight)
updateTableHeight()

// 统一form声明
const form = reactive({
  id: null,
  factorName: '',
  factorCode: '',
  factorType: '',
  dataSourceType: '',
  frequency: '',
  enabled: true,
  description: '',
  dataSourceConfig: '',
  pythonScript: ''
})

const searchForm = reactive({
  factorName: '',
  factorCode: '',
  enabled: null
})
const pagination = reactive({ current: 1, size: 20, total: 0 })
const statistics = reactive({ totalFactors: 0, enabledFactors: 0, disabledFactors: 0, todayUpdates: 0 })
const factors = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentFactor = ref(null)
const factorsDialogVisible = ref(false)
const navDataList = ref([])
const topFormRef = ref(null)
const topForm = reactive({
  fundCode: '',
  startDate: '',
  endDate: ''
})
const factorDialogVisible = ref(false)
const factorFormRef = ref(null)
const factorForm = reactive({
  factorCode: '',
  factorName: '',
  factorType: '',
  fundCode: '',
  value: null,
  description: '',
  enabled: true,
  createdBy: '',
  updatedBy: ''
})

const factorRules = {
  factorCode: [{ required: true, message: '因子代码不能为空', trigger: 'blur' }],
  factorName: [{ required: true, message: '因子名称不能为空', trigger: 'blur' }],
  factorType: [{ required: true, message: '请选择因子类型', trigger: 'change' }],
  fundCode: [{ required: true, message: '基金代码不能为空', trigger: 'blur' }],
  value: [{ required: true, message: '因子值不能为空', trigger: 'blur' }]
}

const submitFactorForm = () => {
  factorFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await axios.post('http://localhost:8080/factor/factors/batch', [factorForm])
        ElMessage.success('保存成功')
        factorDialogVisible.value = false
      } catch (e) {
        ElMessage.error('保存失败，请检查因子代码是否已经存在')
      }
    }
  })
}
const factorTab = ref('base')
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const calculationDialogVisible = ref(false)
const calculationResult = ref([])
const fundInfoDialogVisible = ref(false)
const factorCalcResult = ref([])

const factorNames = [
  { name: '简单收益率因子', type: '收益类' },
  { name: '年化收益率因子', type: '收益类' },
  { name: '对数收益率因子', type: '收益类' },
  { name: '波动率因子', type: '风险类' },
  { name: '夏普比率因子', type: '风险类' },
  { name: '最大回撤因子', type: '风险类' },
  { name: '下行风险因子', type: '风险类' },
  { name: '相对强弱指数因子', type: '技术类' },
  { name: '移动平均值因子', type: '趋势类' },
  { name: '申购开放频率因子', type: '流动性类' },
  { name: '赎回开放频率因子', type: '流动性类' }
];

const onFactorTypeChange = () => {
  loadFactors()
}

const loadFactors = async () => {
  loading.value = true
  let url = ''
  if (factorTab.value === 'base') {
    url = 'http://localhost:8080/factor/factors/OnPage'
  } else if (factorTab.value === 'derived') {
    url = 'http://localhost:8080/derived/derived-factor/page'
  } else if (factorTab.value === 'style') {
    url = 'http://localhost:8080/style/style-factor/page'
  }
  try {
    const res = await axios.get(url, { params: { page: pagination.current - 1, size: pagination.size, ...searchForm } })
    factors.value = res.data.content
    pagination.total = res.data.totalElements
    statistics.totalFactors = pagination.total
    statistics.enabledFactors = factors.value.filter(f => f.enabled).length
    statistics.disabledFactors = pagination.total - statistics.enabledFactors
    statistics.todayUpdates = Math.floor(Math.random() * 10) + 1
  } catch (e) {
    ElMessage.error('加载因子失败')
  } finally {
    loading.value = false
  }
}
const searchFactors = () => { pagination.current = 1; loadFactors() }
const resetSearch = () => { Object.assign(searchForm, { factorCode: '', factorName: '', factorType: '', dataSourceType: '', enabled: null }); pagination.current = 1; loadFactors() }
const handleSizeChange = s => { pagination.size = s; pagination.current = 1; loadFactors() }
const handleCurrentChange = c => { pagination.current = c; loadFactors() }

const openAddFactorDialog = () => {
  console.log('打开弹窗', factorDialogVisible.value)
  Object.assign(factorForm, {
    factorCode: '',
    factorName: '',
    factorType: '',
    fundCode: '',
    value: null,
    description: '',
    enabled: true,
    createdBy: '',
    updatedBy: ''
  })
  factorDialogVisible.value = true
}
const openEditDialog = row => { Object.assign(form, row); dialogTitle.value = '编辑因子'; dialogVisible.value = true }
const toggleStatus = async row => { await axios.put(`http://localhost:8080/factor/factors/${row.id}/status`, { enabled: !row.enabled }); await loadFactors() }
const deleteFactor = (rowOrId) => {
  let id = typeof rowOrId === 'object' ? rowOrId.id : rowOrId;
  let type = factorTab.value;
  console.log('当前tab类型:', type);
  let url = '';
  let reload = loadFactors;
  if (type === 'base') {
    url = `http://localhost:8080/factor/factor/${id}`;
    reload = loadFactors;
  } else if (type === 'derived') {
    url = `http://localhost:8080/derived/dev/deleteById/${id}`;
    reload = loadFactors;
  } else if (type === 'style') {
    url = `http://localhost:8080/style/Style/deleteById/${id}`;
    reload = loadFactors;
  } else {
    ElMessage.error('未知类型');
    return;
  }
  ElMessageBox.confirm('确认删除?', '提示', { type: 'warning' })
    .then(async () => {
      await axios.delete(url);
      await reload();
    });
}
const exportFactors = () => {
  ElMessage.info('导出功能待实现')
}

const handleSelectionChange = () => {}
const getFactorTypeColor = type => type === 'BASIC' ? 'success' : type === 'DERIVED' ? 'warning' : 'info'
const getFactorTypeLabel = type => type === 'BASIC' ? '基础因子' : type === 'DERIVED' ? '衍生因子' : type === 'STYLE' ? '风格因子' : type
const getDataSourceColor = type => type === 'TIANJIN' ? 'success' : type === 'WIND' ? 'info' : 'default'
const getDataSourceLabel = type => type === 'TIANJIN' ? '天天基金网' : type === 'WIND' ? 'Wind数据库' : type
const getFrequencyLabel = freq => freq === 'DAILY' ? '日频' : freq === 'WEEKLY' ? '周频' : freq === 'MONTHLY' ? '月频' : freq === 'QUARTERLY' ? '季频' : freq
const formatDateTime = val => val ? new Date(val).toLocaleString() : ''
const showFundDetails = async () => {
  try {
    if (!topForm.fundCode || !topForm.startDate || !topForm.endDate) {
      ElMessage.error('请填写完整的基金代码、开始日期和结束日期')
      return
    }
    const response = await axios.get(`http://localhost:8080/factor/factor/getSimpleJJ/${topForm.fundCode}/${topForm.startDate}/${topForm.endDate}`)
    if (Array.isArray(response.data)) {
      navDataList.value = response.data
      fundInfoDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取基金信息失败')
  }
}

const handleTabChange = () => {
  loadFactors()
}

watch(factorTab, () => {
  loadFactors()
})

const percentIndex = [0, 1, 2, 3, 5, 6, 9, 10]; // 这些下标为百分比因子
const calculateFactors = async () => {
  if (!topForm.fundCode || !topForm.startDate || !topForm.endDate) {
    ElMessage.error('请填写完整的基金代码、开始日期和结束日期')
    return
  }
  try {
    loading.value = true;
    const response = await axios.get(`http://localhost:8080/factor/factor/getSimpleFactor/${topForm.fundCode}/${topForm.startDate}/${topForm.endDate}`)
    if (Array.isArray(response.data)) {
      factorCalcResult.value = response.data.map((v, i) => ({
        name: factorNames[i]?.name || `因子${i+1}`,
        type: factorNames[i]?.type || '',
        value: v !== undefined && v !== null
          ? (percentIndex.includes(i) ? (v * 100).toFixed(3) + '%' : v.toFixed(3))
          : 'N/A'
      }))
      factorsDialogVisible.value = true
      loading.value = false;
    }
  } catch (error) {
    ElMessage.error('计算因子失败')
    loading.value = false;
  }
}
</script>

<style scoped>
.factor-page.no-scroll {
  height: 100vh;
  min-height: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.top-search-card {
  flex-shrink: 0;
}
.factor-main-card {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  position: relative;
  padding-bottom: 60px;
}
.factor-table-wrapper {
  flex: 1 1 0;
  min-height: 0;
  overflow: auto;
}
.el-table {
  height: 100% !important;
  min-height: 0;
}
body, html, #app {
  height: 100%;
  min-height: 0;
  overflow: hidden;
}
.factor-page { padding:20px }
.home-page { background:#f5f7fa }
.top-search-card {
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 4px 10px 0 10px;
  min-height: unset;
  box-shadow: 0 1px 4px rgba(0,0,0,0.03);
}
.top-search-form {
  margin-bottom: 0;
  padding: 0;
  min-height: unset;
}
.top-search-form .el-form-item {
  margin-bottom: 4px;
}
.main-card.module-card{background:#fff;border-radius:8px;padding:20px}
.card-header{display:flex;justify-content:space-between;align-items:center;padding:10px 0}
.page-title{display:flex;align-items:center;gap:6px;font-size:18px;font-weight:bold}
.header-right> *{margin-left:10px}
.search-section{margin:20px 0}
.table-section{overflow:hidden}
.el-table{width:100%!important}
.empty-placeholder{height:100%;display:flex;justify-content:center;align-items:center;flex-direction:column}
.card-pagination-fixed {
  position: absolute;
  right: 30px;
  bottom: 20px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  text-align: right;
  z-index: 2;
  width: auto;
  display: flex;
  justify-content: flex-end;
  padding-bottom: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0; /* 原来是 10px 0，改为 4px 上下 */
  line-height: 1;
}
.factor-name{display:flex;align-items:center;gap:4px}
.update-time{display:flex;align-items:center;gap:4px}
.dialog-footer{text-align:right}
.el-button-group .el-button{margin-right:0!important}
.el-dialog__footer{padding-right:24px}
.search-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 6px;
  color: #333;
  letter-spacing: 2px;
}
.factor-type-tabs {
  margin-bottom: 8px;
}
@media (max-width: 900px) {
  .stat-card, .main-card.module-card { padding: 10px; }
  .stat-number { font-size: 18px; }
  .page-title { font-size: 16px; }
}
</style>